import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import "./TicketSales.css";

export default function TicketSales() {
  const [scheduleDetails, setScheduleDetails] = useState(null);
  const [schedules, setSchedules] = useState([]);
  const [movies, setMovies] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedSeats, setSelectedSeats] = useState([]);
  const [selectedScheduleId, setSelectedScheduleId] = useState(null);
  const { scheduleId } = useParams();
  const navigate = useNavigate();

  // 获取所有排片和电影数据
  useEffect(() => {
    if (!scheduleId) {
      Promise.all([
        fetch("http://localhost:8080/api/schedules").then((response) => {
          if (!response.ok) {
            throw new Error("获取排片列表失败");
          }
          return response.json();
        }),
        fetch("http://localhost:8080/api/movies").then((response) => {
          if (!response.ok) {
            throw new Error("获取电影列表失败");
          }
          return response.json();
        }),
      ])
        .then(([scheduleData, movieData]) => {
          const movieMap = {};
          movieData.forEach((movie) => {
            movieMap[movie.id] = movie.title;
          });
          setSchedules(scheduleData);
          setMovies(movieMap);
          setLoading(false);
        })
        .catch((error) => {
          setError(error.message);
          setLoading(false);
        });
    } else {
      // 获取特定排片详情
      fetch(`http://localhost:8080/api/schedules/${scheduleId}/details`)
        .then((response) => {
          if (!response.ok) {
            throw new Error("获取排片详情失败");
          }
          return response.json();
        })
        .then((data) => {
          setScheduleDetails(data);
          setLoading(false);
        })
        .catch((error) => {
          setError(error.message);
          setLoading(false);
        });
    }
  }, [scheduleId]);

  // 处理排片选择
  const handleScheduleSelect = (e) => {
    const id = e.target.value;
    setSelectedScheduleId(id);
  };

  // 确认选择排片
  const confirmScheduleSelection = () => {
    if (selectedScheduleId) {
      navigate(`/tickets/sales/${selectedScheduleId}`);
    } else {
      alert("请选择一个排片");
    }
  };

  // 处理座位选择
  const handleSeatClick = (seat) => {
    if (seat.sold) return; // 已售出的座位不能选择

    setSelectedSeats((prev) => {
      if (prev.some((s) => s.id === seat.id)) {
        return prev.filter((s) => s.id !== seat.id); // 取消选择
      } else {
        return [...prev, seat]; // 添加选择
      }
    });
  };

  // 添加购票处理函数 - 移到组件内部
  const handlePurchase = (selectedSeats) => {
    const phoneInput = document.getElementById("phone");
    const phone = phoneInput.value.trim();

    // 删除手机号验证代码
    // if (!/^1[3-9]\d{9}$/.test(phone)) {
    //   alert("请输入有效的手机号");
    //   return;
    // }

    // 为每个选中的座位发送购票请求
    selectedSeats.forEach((seat) => {
      const requestBody = {
        scheduleId: scheduleDetails.id,
        rowNo: seat.rowNo,
        colNo: seat.colNo,
        phone: phone,
      };

      fetch("http://localhost:8080/api/tickets/purchase", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestBody),
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error("购票失败");
          }
          return response.json();
        })
        .then((data) => {
          // 显示购票成功信息
          alert(
            `购票成功！\n电影: ${data.schedule.movie.title}\n场次: ${new Date(
              data.schedule.start_time
            ).toLocaleString()}\n座位: ${data.rowNo}排${
              data.colNo
            }座\n票价: ${data.schedule.price.toFixed(
              2
            )}元\n购票时间: ${new Date(data.soldAt).toLocaleString()}`
          );

          // 更新座位状态
          handleSeatClick(seat); // 取消选中状态

          // 刷新页面或更新座位数据
          window.location.reload();
        })
        .catch((error) => {
          alert("购票失败: " + error.message);
        });
    });
  };

  // 生成座位矩阵 (8行10列)
  const renderSeatMatrix = () => {
    if (!scheduleDetails || !scheduleDetails.seats) return null;

    // 将座位按行列排序
    const sortedSeats = [...scheduleDetails.seats].sort((a, b) => {
      if (a.rowNo !== b.rowNo) return a.rowNo - b.rowNo;
      return a.colNo - b.colNo;
    });

    // 构建8x10的座位矩阵
    const matrix = Array(8)
      .fill()
      .map(() => Array(10).fill(null));
    sortedSeats.forEach((seat) => {
      // 注意：rowNo和colNo可能从1开始，这里需要减1转为索引
      if (
        seat.rowNo >= 1 &&
        seat.rowNo <= 8 &&
        seat.colNo >= 1 &&
        seat.colNo <= 10
      ) {
        matrix[seat.rowNo - 1][seat.colNo - 1] = seat;
      }
    });

    return matrix.map((row, rowIndex) => (
      <div key={rowIndex} className="seat-row">
        <div className="row-label">{rowIndex + 1}</div>
        {row.map((seat, colIndex) => (
          <div
            key={`${rowIndex}-${colIndex}`}
            className={`seat ${
              seat
                ? seat.sold
                  ? "sold"
                  : selectedSeats.some((s) => s.id === seat.id)
                  ? "selected"
                  : "available"
                : "unavailable"
            }
            `}
            onClick={() => seat && !seat.sold && handleSeatClick(seat)}
          >
            {seat ? seat.colNo : ""}
          </div>
        ))}
      </div>
    ));
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error">错误: {error}</div>;
  }

  // 如果没有选择排片ID，显示排片选择界面
  if (!scheduleId) {
    return (
      <div className="ticket-sales-container">
        <h1>选择排片</h1>
        <div className="schedule-selection">
          <label htmlFor="schedule-select">请选择排片:</label>
          <select
            id="schedule-select"
            value={selectedScheduleId || ""}
            onChange={handleScheduleSelect}
          >
            <option value="">-- 请选择 --</option>
            {schedules.map((schedule) => (
              <option key={schedule.id} value={schedule.id}>
                {movies[schedule.movie_id] || "未知电影"} -{" "}
                {new Date(schedule.start_time).toLocaleString()} -{" "}
                {schedule.price.toFixed(2)}元
              </option>
            ))}
          </select>
          <button onClick={confirmScheduleSelection}>确认选择</button>
        </div>
      </div>
    );
  }

  // 确保scheduleDetails不为null
  if (!scheduleDetails) {
    return <div className="loading">加载排片详情中...</div>;
  }

  // 显示座位选择界面
  return (
    <div className="ticket-sales-container">
      <div className="schedule-details">
        <h2>
          {scheduleDetails.movie_title ||
            movies[scheduleDetails.movie_id] ||
            "未知电影"}
        </h2>
        <p>排片ID: {scheduleDetails.id}</p>
        <p>电影ID: {scheduleDetails.movie_id}</p>
        <p>开始时间: {new Date(scheduleDetails.start_time).toLocaleString()}</p>
        <p>票价: {scheduleDetails.price.toFixed(2)}元</p>
      </div>

      <div className="seat-selection">
        <div className="screen">屏幕</div>
        <div className="seat-matrix">{renderSeatMatrix()}</div>

        <div className="legend">
          <div className="legend-item">
            <div className="seat available"></div>
            <span>可售</span>
          </div>
          <div className="legend-item">
            <div className="seat sold"></div>
            <span>已售</span>
          </div>
          <div className="legend-item">
            <div className="seat selected"></div>
            <span>已选</span>
          </div>
          <div className="legend-item">
            <div className="seat unavailable"></div>
            <span>不可用</span>
          </div>
        </div>
      </div>

      <div className="checkout">
        <h3>选座信息</h3>
        {selectedSeats.length > 0 ? (
          <div>
            <p>
              已选座位:{" "}
              {selectedSeats
                .map((seat) => `(${seat.rowNo},${seat.colNo})`)
                .join(", ")}
            </p>
            <p>
              总价: {selectedSeats.length * scheduleDetails.price.toFixed(2)}元
            </p>
            {/* 添加手机号输入框 */}
            <div className="phone-input">
              <label htmlFor="phone">手机号:</label>
              <input
                type="tel"
                id="phone"
                placeholder="请输入手机号"
                // 移除pattern属性
                // pattern="^1[3-9]\d{9}$"
                required
              />
            </div>
            <button
              className="order-btn"
              onClick={() => handlePurchase(selectedSeats)}
            >
              确认购票
            </button>
          </div>
        ) : (
          <p>请选择座位</p>
        )}
      </div>
    </div>
  );
}
